package com.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.common.Result;
import com.demo.entity.Item;
import com.demo.entity.Item;
import com.demo.mapper.ItemMapper;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 科研项目表
 */
@RestController
@RequestMapping("/item")
public class ItemController {
  /**
   * 服务对象
   */
  @Resource
  ItemMapper itemMapper;
  
  // 新增
  @PostMapping
  public Result<?> insert(@RequestBody Item item) {
    try {
      itemMapper.insert(item);
      return Result.success();
    } catch (Exception e) {
      return Result.error("201","");
    }
   
  }
  
  //  删除 ById
  @DeleteMapping("/{id}")
  public Result<?> delete(@PathVariable Integer id) {
    itemMapper.deleteById(id);
    return Result.success();
  }
  
  // 修改
  @PutMapping
  public Result<?> updata(@RequestBody Item item) {
    try {
      itemMapper.updateById(item);
      return Result.success();
    } catch (Exception e) {
      return Result.error("201","" );
    }
    
  }
  
  /**
   * 分页,默认1页,10个数据,  默认根据 项目名称 iname 查询
   *
   * @param pageNum  页数
   * @param pageSize 页面显示数
   * @param search   搜索关键词
   * @param sort     搜索类别
   * @return
   */
  @GetMapping
  public Result<?> findPageByaName(@RequestParam(defaultValue = "1") Integer pageNum,
                                   @RequestParam(defaultValue = "10") Integer pageSize,
                                   @RequestParam(defaultValue = "") String search,
                                   @RequestParam(defaultValue = "Iname") String sort) {
    LambdaQueryWrapper<Item> wrapper = Wrappers.<Item>lambdaQuery();
    //根据Id逆序排列
    wrapper.orderByDesc(Item::getId);
    if (StrUtil.isNotBlank(search)) {
      switch (sort) {
        case "Iname": //根据项目名称
          wrapper.like(Item::getIname, search);
          break;
        case "Ino"://项目编号
          wrapper.like(Item::getIno, search);
          break;
        case "Icategory"://项目类别
          wrapper.like(Item::getIcategory, search);
          break;
        case "Leader"://负责人
          wrapper.like(Item::getLeader, search);
          break;
        case "Member"://课题组成员
          wrapper.like(Item::getMember, search);
          break;
      }
    }
    
    Page<Item> AdminPage = itemMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
    return Result.success(AdminPage);
  }
  
  // 根据ino 查询是否有这个主键
  @GetMapping("/ino/{ino}")
  public Result<?> getKey(@PathVariable String ino) {
    Item i = itemMapper.selectOne(Wrappers.<Item>lambdaQuery().eq(Item::getIno, ino));
    if(i == null){
      //表示不含有此 主键
      return Result.success();
    }
    //表示表中已存在此 主键
    return Result.errorData("201", i);
  }
  
  
}

